//
//  UIScrollView+SecondaryDelegate.m
//  PYMKDynamicUI
//
//  Created by lixuelin on 2021/3/25.
//

#import "UIScrollView+SecondaryDelegate.h"
#import "KSScrollViewDelegateProxy.h"
#import <objc/runtime.h>

@interface UIScrollView ()

@property (nonatomic, strong) KSScrollViewDelegateProxy *ks_ScrollDelegateProxy;

@end

@implementation UIScrollView (SecondaryDelegate)

+ (void)load {
    [self swizzledSelector:@selector(expose_setDelegate:) originalSelector:@selector(setDelegate:)];
}

- (void)expose_setDelegate:(id<UIScrollViewDelegate>)delegate {
    // need hook
    if (self.ks_ScrollDelegateProxy) {
        if (self.ks_ScrollDelegateProxy != delegate) {
            self.ks_ScrollDelegateProxy.ks_PrimaryDelegate = delegate;
        }
        [self expose_setDelegate:self.ks_ScrollDelegateProxy];
    } else { // normal process
        [self expose_setDelegate:delegate];
    }
}

+ (void)swizzledSelector:(SEL)swizzledSelector originalSelector:(SEL)originalSelector {
    Class class = [self class];
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    BOOL didAddMethod =
    class_addMethod(class,
                    originalSelector,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

- (void)ks_et_addDelegate:(id)delegate {
    if (!self.ks_ScrollDelegateProxy) {
        self.ks_ScrollDelegateProxy = [KSScrollViewDelegateProxy alloc];
        self.ks_ScrollDelegateProxy.ks_PrimaryDelegate = self.delegate;
    }
    [self.ks_ScrollDelegateProxy addDelegate:delegate];
    if (self.delegate != self.ks_ScrollDelegateProxy) {
        self.delegate = self.ks_ScrollDelegateProxy;
    }
}

- (KSScrollViewDelegateProxy *)ks_ScrollDelegateProxy {
    return objc_getAssociatedObject(self, @selector(ks_ScrollDelegateProxy));
}

- (void)setKs_ScrollDelegateProxy:(KSScrollViewDelegateProxy *)ks_ScrollDelegateProxy {
    objc_setAssociatedObject(self, @selector(ks_ScrollDelegateProxy), ks_ScrollDelegateProxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
